<template>
  <div class="self-introduction-step">
    <div class="step-header">
      <h3>自我介绍</h3>
      <p>请填写一段自我推荐文本，展示您的优秀品质和能力</p>
    </div>

    <div class="introduction-form">
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="0"
      >
        <el-form-item prop="content">
          <div class="textarea-wrapper">
            <el-input
              v-model="form.content"
              type="textarea"
              :placeholder="placeholder"
              :rows="12"
              resize="none"
              maxlength="300"
              show-word-limit
              @input="handleContentChange"
            />
            <div class="word-count">
              <div class="count-info" :class="getCountStatus()">
                <div class="count-icon" :class="getCountStatus()">
                  {{ getCountIcon() }}
                </div>
                <span>{{ wordCount }}/300字</span>
              </div>
              <div v-if="wordCount < 100" class="requirement">
                还需要 {{ 100 - wordCount }} 字
              </div>
              <div v-else-if="wordCount >= 100 && wordCount <= 300" class="success-tip">
                字数符合要求 ✓
              </div>
            </div>
          </div>
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存自我介绍
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 写作提示 -->
    <div class="writing-tips">
      <h4>写作建议</h4>
      <ul>
        <li>突出个人优势和特长，展现积极向上的品质</li>
        <li>结合具体经历说明学习能力和工作能力</li>
        <li>表达对未来工作的热情和期待</li>
        <li>语言简洁明了，逻辑清晰，真诚自然</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, type FormRules, type FormInstance } from 'element-plus'
import { selfIntroductionApi, type SelfIntroduction } from '@/api/resume'

// Props
interface Props {
  resumeId: number
}

// Emits
interface Emits {
  (e: 'completed', completed: boolean): void
  (e: 'data-saved'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const form = ref<SelfIntroduction>({
  content: ''
})

// Placeholder示例文本
const placeholder = `我是一名积极向上、热爱学习的大学生，具备扎实的专业基础和良好的团队协作能力。在校期间，我始终保持优异的学习成绩，积极参与各类实践活动和项目开发，不断提升自己的专业技能和综合素质。

我性格开朗乐观，善于沟通交流，能够快速适应新环境并融入团队。面对挑战时，我总是保持积极的心态，勇于尝试和创新。我相信通过不懈的努力和持续的学习，能够在未来的工作中发挥自己的价值，为团队和公司的发展贡献力量。

我期待能够加入贵公司，在实际工作中继续成长和进步，与团队一起创造更大的价值。`

// 字数统计
const wordCount = computed(() => {
  return form.value.content ? form.value.content.trim().length : 0
})

// 表单验证规则
const rules: FormRules = {
  content: [
    { required: true, message: '请填写自我介绍内容', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || !value.trim()) {
          callback(new Error('自我介绍内容不能为空'))
          return
        }

        const length = value.trim().length
        if (length < 100) {
          callback(new Error(`自我介绍内容不能少于100字，当前${length}字`))
          return
        }

        if (length > 300) {
          callback(new Error(`自我介绍内容不能超过300字，当前${length}字`))
          return
        }

        callback()
      },
      trigger: 'blur'
    }
  ]
}

// 监听内容变化，判断是否完成
watch(() => form.value.content, () => {
  checkCompletion()
}, { deep: true })

// 检查完成状态
const checkCompletion = () => {
  const isCompleted = wordCount.value >= 100 && wordCount.value <= 300
  emit('completed', isCompleted)
}

// 处理内容变化
const handleContentChange = () => {
  // 实时字数统计已通过computed处理
}

// 获取字数统计状态
const getCountStatus = () => {
  if (wordCount.value < 100) return 'error'
  if (wordCount.value > 300) return 'error'
  return 'success'
}

// 获取字数统计图标
const getCountIcon = () => {
  if (wordCount.value < 100) return '!'
  if (wordCount.value > 300) return '!'
  return '✓'
}

// 获取自我介绍
const fetchSelfIntroduction = async () => {
  loading.value = true
  try {
    const response = await selfIntroductionApi.getSelfIntroduction(props.resumeId)
    const data = response.data || response

    console.log('获取自我介绍响应:', data)

    // 处理不同的响应格式
    let selfIntroduction = null

    if (Array.isArray(data)) {
      // 如果返回的是数组，取第一个元素
      selfIntroduction = data.length > 0 ? data[0] : null
    } else if (data && data.results && Array.isArray(data.results)) {
      // 如果返回的是分页格式
      selfIntroduction = data.results.length > 0 ? data.results[0] : null
    } else if (data && data.content) {
      // 如果返回的是单个对象
      selfIntroduction = data
    }

    if (selfIntroduction && selfIntroduction.content) {
      form.value = {
        id: selfIntroduction.id,
        content: selfIntroduction.content
      }
      console.log('自我介绍数据已加载:', form.value)
    } else {
      console.log('未找到自我介绍数据')
      // 重置表单
      form.value = {
        content: ''
      }
    }
  } catch (error) {
    console.error('获取自我介绍失败:', error)
    // 如果没有自我介绍记录，保持空白
    form.value = {
      content: ''
    }
  } finally {
    loading.value = false
  }
}

// 保存自我介绍
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    saving.value = true

    try {
      if (form.value.id) {
        // 更新现有记录
        await selfIntroductionApi.updateSelfIntroduction(props.resumeId, form.value.id, form.value)
      } else {
        // 尝试创建新记录
        const response = await selfIntroductionApi.saveSelfIntroduction(props.resumeId, form.value)
        const data = response.data || response
        form.value.id = data.id
      }
    } catch (createError) {
      // 如果创建失败（可能是因为已存在记录），尝试获取现有记录并更新
      if (createError.response?.status === 400 || createError.message?.includes('UNIQUE constraint')) {
        console.log('记录已存在，尝试更新现有记录')

        // 重新获取现有记录
        await fetchSelfIntroduction()

        if (form.value.id) {
          // 如果获取到了现有记录，更新它
          await selfIntroductionApi.updateSelfIntroduction(props.resumeId, form.value.id, {
            content: form.value.content
          })
        } else {
          // 如果仍然没有ID，抛出原始错误
          throw createError
        }
      } else {
        throw createError
      }
    }

    ElMessage.success('自我介绍保存成功')

    // 重新获取数据确保状态同步
    await fetchSelfIntroduction()

    // 触发数据保存事件
    emit('data-saved')

  } catch (error) {
    console.error('保存自我介绍错误:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchSelfIntroduction()
})
</script>

<style lang="scss" scoped>
.self-introduction-step {
  width: 100%;
  max-width: none;
  margin: 0;
  padding: 0 24px;

  .step-header {
    text-align: center;
    margin-bottom: 32px;
    padding: 24px;
    background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
    border-radius: 16px;
    color: var(--el-color-white);
    position: relative;
    overflow: hidden;
    border: 1px solid var(--el-border-color-lighter);

    // 深色模式适配
    html.dark & {
      background: linear-gradient(135deg, var(--el-color-primary-dark-2) 0%, var(--el-color-primary) 100%);
      border-color: var(--el-border-color-dark);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    }

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.1"/><circle cx="10" cy="60" r="0.5" fill="white" opacity="0.1"/><circle cx="90" cy="40" r="0.5" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
      pointer-events: none;
    }

    h3 {
      font-size: 28px;
      font-weight: 700;
      margin: 0 0 12px 0;
      position: relative;
      z-index: 1;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    p {
      font-size: 16px;
      margin: 0;
      opacity: 0.95;
      position: relative;
      z-index: 1;
    }
  }

  .introduction-form {
    margin-bottom: 32px;
    background: var(--el-bg-color);
    border-radius: 16px;
    padding: 24px;
    box-shadow: var(--el-box-shadow-light);
    border: 1px solid var(--el-border-color-lighter);
    width: 100%;

    // 深色模式适配
    html.dark & {
      background: var(--el-bg-color-page);
      border-color: var(--el-border-color-dark);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
    }

    .textarea-wrapper {
      position: relative;
      width: 100%;

      :deep(.el-textarea) {
        width: 100%;

        .el-textarea__inner {
          font-size: 15px;
          line-height: 1.8;
          padding: 20px;
          border-radius: 12px;
          border: 2px solid var(--el-border-color-light);
          background: var(--el-fill-color-extra-light);
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          resize: none;
          width: 100%;
          box-sizing: border-box;
          // 动态计算高度，适应页面空间
          min-height: max(280px, calc(100vh - 600px));
          max-height: calc(100vh - 400px);
          color: var(--el-text-color-primary);

          // 深色模式适配
          html.dark & {
            background: var(--el-fill-color-dark);
            border-color: var(--el-border-color-dark);
            color: var(--el-text-color-primary);
          }

          &:hover {
            border-color: var(--el-color-primary-light-5);
            background: var(--el-fill-color-light);

            html.dark & {
              border-color: var(--el-color-primary-light-3);
              background: var(--el-fill-color);
            }
          }

          &:focus {
            border-color: var(--el-color-primary);
            background: var(--el-bg-color);
            box-shadow: 0 0 0 4px var(--el-color-primary-light-9);
            transform: translateY(-1px);

            html.dark & {
              background: var(--el-bg-color-page);
              box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.2);
            }
          }

          &::placeholder {
            color: var(--el-text-color-placeholder);
            line-height: 1.8;
            font-style: italic;
          }
        }

        .el-textarea__count {
          display: none;
        }
      }

      .word-count {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 16px;
        padding: 12px 16px;
        background: var(--el-fill-color-extra-light);
        border-radius: 8px;
        border: 1px solid var(--el-border-color-lighter);

        // 深色模式适配
        html.dark & {
          background: var(--el-fill-color-dark);
          border-color: var(--el-border-color-dark);
        }

        .count-info {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          font-weight: 500;
          color: var(--el-text-color-regular);

          &.error {
            color: var(--el-color-danger);
          }

          &.success {
            color: var(--el-color-success);
          }

          .count-icon {
            width: 16px;
            height: 16px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            color: var(--el-color-white);
            background: var(--el-text-color-regular);

            &.error {
              background: var(--el-color-danger);
            }

            &.success {
              background: var(--el-color-success);
            }
          }
        }

        .requirement {
          font-size: 12px;
          color: var(--el-color-warning);
          background: var(--el-color-warning-light-9);
          padding: 4px 8px;
          border-radius: 4px;
          font-weight: 500;
          border: 1px solid var(--el-color-warning-light-7);
        }

        .success-tip {
          font-size: 12px;
          color: var(--el-color-success);
          background: var(--el-color-success-light-9);
          padding: 4px 8px;
          border-radius: 4px;
          font-weight: 500;
          border: 1px solid var(--el-color-success-light-7);
        }
      }
    }

    .form-actions {
      text-align: center;
      margin-top: 32px;

      :deep(.el-button) {
        padding: 12px 32px;
        font-size: 16px;
        font-weight: 600;
        border-radius: 12px;
        background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
        border: none;
        color: var(--el-color-white);
        box-shadow: 0 4px 16px var(--el-color-primary-light-8);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        // 深色模式适配
        html.dark & {
          background: linear-gradient(135deg, var(--el-color-primary-dark-2) 0%, var(--el-color-primary) 100%);
          box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px var(--el-color-primary-light-7);

          html.dark & {
            box-shadow: 0 8px 24px rgba(64, 158, 255, 0.4);
          }
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }

  .writing-tips {
    background: linear-gradient(135deg, var(--el-color-info-light-9) 0%, var(--el-color-primary-light-9) 100%);
    border-radius: 16px;
    padding: 28px;
    border: 1px solid var(--el-color-primary-light-7);
    position: relative;
    overflow: hidden;

    // 深色模式适配
    html.dark & {
      background: linear-gradient(135deg, var(--el-fill-color-dark) 0%, var(--el-fill-color) 100%);
      border-color: var(--el-border-color-dark);
    }

    &::before {
      content: '💡';
      position: absolute;
      top: 20px;
      right: 20px;
      font-size: 24px;
      opacity: 0.6;
    }

    h4 {
      font-size: 18px;
      font-weight: 700;
      color: var(--el-color-primary);
      margin: 0 0 16px 0;
      display: flex;
      align-items: center;
      gap: 8px;

      // 深色模式适配
      html.dark & {
        color: var(--el-color-primary-light-3);
      }

      &::before {
        content: '✨';
        font-size: 20px;
      }
    }

    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      color: var(--el-text-color-primary);

      li {
        margin-bottom: 12px;
        line-height: 1.6;
        padding-left: 24px;
        position: relative;
        font-size: 14px;

        &::before {
          content: '▸';
          position: absolute;
          left: 0;
          color: var(--el-color-primary);
          font-weight: bold;
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}

// 平板适配
@media (max-width: 1024px) {
  .self-introduction-step {
    padding: 0 16px;

    .introduction-form {
      .textarea-wrapper {
        :deep(.el-textarea) {
          .el-textarea__inner {
            min-height: max(240px, calc(100vh - 650px));
            max-height: calc(100vh - 450px);
          }
        }
      }
    }
  }
}

// 移动端适配
@media (max-width: 768px) {
  .self-introduction-step {
    padding: 0 12px;

    .step-header {
      padding: 20px 16px;
      margin-bottom: 20px;

      h3 {
        font-size: 24px;
      }

      p {
        font-size: 14px;
      }
    }

    .introduction-form {
      padding: 16px;
      margin-bottom: 20px;

      .textarea-wrapper {
        :deep(.el-textarea) {
          .el-textarea__inner {
            padding: 16px;
            font-size: 14px;
            min-height: max(200px, calc(100vh - 500px));
            max-height: calc(100vh - 300px);
          }
        }

        .word-count {
          flex-direction: column;
          gap: 8px;
          align-items: flex-start;
          padding: 10px 12px;
        }
      }

      .form-actions {
        margin-top: 20px;

        :deep(.el-button) {
          width: 100%;
          padding: 14px 16px;
          font-size: 15px;
        }
      }
    }

    .writing-tips {
      padding: 16px;

      h4 {
        font-size: 16px;
      }

      ul li {
        font-size: 13px;
        padding-left: 20px;
      }
    }
  }
}

// 小屏幕适配
@media (max-width: 480px) {
  .self-introduction-step {
    padding: 0 8px;

    .step-header {
      padding: 16px 12px;
      margin-bottom: 16px;

      h3 {
        font-size: 20px;
      }

      p {
        font-size: 13px;
      }
    }

    .introduction-form {
      padding: 12px;

      .textarea-wrapper {
        :deep(.el-textarea) {
          .el-textarea__inner {
            padding: 12px;
            font-size: 13px;
            min-height: max(180px, calc(100vh - 450px));
          }
        }
      }
    }

    .writing-tips {
      padding: 12px;

      h4 {
        font-size: 14px;
      }

      ul li {
        font-size: 12px;
        padding-left: 16px;
      }
    }
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.self-introduction-step > * {
  animation: fadeInUp 0.6s ease-out;
}

.self-introduction-step > *:nth-child(2) {
  animation-delay: 0.1s;
}

.self-introduction-step > *:nth-child(3) {
  animation-delay: 0.2s;
}
</style>
